﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using System.Security.Principal;

namespace MvcApp.CommonSupport.Filter
{
    /// <summary>
    /// 权限拦截
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AuthorizeFilterAttribute : ActionFilterAttribute
    {
        public string ModuleName { get; set; }
        public int PermisionType { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            var path = filterContext.HttpContext.Request.Path.ToLower();
            if (path == "/" || path == "/Home/LogOn".ToLower() || path == "/Home/UserLogOn".ToLower())
                return;//忽略对Login登录页的权限判定

            //注：如果未登录直接在URL输入功能权限地址提示不是很友好；如果登录后输入未维护的功能权限地址，那么也可以访问，这个可能会有安全问题
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();//直接URL输入的页面地址跳转到登陆页
            }
            else
            {
                if (!AuthorizeCore(filterContext))
                {
                    filterContext.Result = new ContentResult { Content = @"<script>alert('抱歉,你不具有当前操作的权限！');</script>" };//功能权限弹出提示框
                }
            }
        }

        //权限判断业务逻辑
        protected virtual bool AuthorizeCore(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                return false;//判定用户是否登录
            }

            var user = new CurrentUser();//获取当前用户信息
            if (!user.ActionPermission.ContainsKey(this.ModuleName))
            {
                return false;
            }
            if ((Convert.ToInt32(user.ActionPermission[this.ModuleName]) & this.PermisionType)
                != this.PermisionType)
            {
                return false;
            }
            return true;
        }
    }
}
